package com.mipo;

import org.apache.http.HttpStatus;
import org.apache.http.client.CookieStore;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.util.EntityUtils;

public class HttpClientWithCookie {
	public static void main(String[] args) throws Exception {
		String ticket = say("http://open.jztest.changyan.cn/sso/login?service=http://10.4.0.72/App.ResourceCloud/addons/library/sso/ssoservice.php", "TGT-3326-64qPJdz13MdpRmFq1GFUURKxUd3TcxSNmKMpf7rpwAHf1dvixs-open.jztest.changyan.cn");
		System.out.println(ticket);
	}
	
	public static String say(String url, String tgt)throws Exception {
		System.out.println("jjj");
		String ret="";
		//添加JSESSIONID的Cookie
	    CookieStore cookieStore = new BasicCookieStore();
	    BasicClientCookie cookie = new BasicClientCookie("CASTGC", tgt);
	    cookie.setVersion(0);
	    cookie.setDomain("open.jztest.changyan.cn");
	    cookie.setPath("/sso/");
	    cookieStore.addCookie(cookie);
	    CloseableHttpClient httpclient = HttpClients.custom()
	            .setDefaultCookieStore(cookieStore)//设置Cookie
	            .build();

	    RequestConfig requestConfig = RequestConfig.custom()
	            .setSocketTimeout(5000)  
	            .setConnectTimeout(5000)  
	            .setConnectionRequestTimeout(5000)  
	            .build(); 

	    HttpGet httpGet = new HttpGet(url);
	    //设置Header的User-Agent
	    httpGet.setHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36");
	    httpGet.setConfig(requestConfig);
	    CloseableHttpResponse httpResp = httpclient.execute(httpGet);
	    try {
	        int statusCode = httpResp.getStatusLine().getStatusCode();
	        if (statusCode == HttpStatus.SC_OK) {
	            System.out.println("成功");
	            ret = EntityUtils.toString(httpResp.getEntity()); // 将返回报文实体转换为字符�?
	            System.out.println(ret);
	            String ticket = ret.substring(ret.indexOf("\"st\": \"")+7, ret.indexOf("\" } \\"));
	            ret = ticket;
	    		System.out.println("返回的报文为�?" + ticket);
	        }
	    } catch (Exception e) {

	    } finally {
	        httpResp.close();
	    }
	    return ret;
	}
	
	
}
